/*
 * @Description:
 * @Author: Jevon
 * @Date: 2021-11-25 11:12:53
 */
import DataMode from '.';
import VuiMutliTagSelect from '../vui/buttons/tag-select';
export default class DataModeGroup extends DataMode {
  constructor(data, onclick) {
    super();
    this.className = {
      item: 'data-mode',
      line: 'data-mode-line',
      group: 'group-data'
    };
    this.config = {
      group: '分组数据',
      groupColumn: '分组字段：'
    };
    this.data = data;
    this.onclick = onclick || (_ => {});
  }

  init() {
    this.container = this.createGroup();
    return this;
  }

  // 分组数据
  createGroup() {
    const cls = this.className;
    const config = this.config;
    // 容器
    const div = this.createDiv(cls.item);
    // 状态单选框
    this.createTitle(cls.group, config.group, div);

    // 分组字段
    const groupLine = this.createDiv(cls.line);
    const selectConfig = {
      id: 'group-select',
      showcaseWidth: 240,
      dropdownWidth: 240,
      defaultValue: '请选择...',
      options: this.data2option(this.data),
      title: config.groupColumn,
      showTitle: true,
      action: _ => {}
    };
    const select = new VuiMutliTagSelect(selectConfig).init();
    select.setMargin('0px 8px');
    select.appendTo(groupLine);
    div.appendChild(groupLine);

    // 变更按钮
    let disabled = false;
    const btn = this.createBtn(evt => {
      // 点击事件
      if (disabled) return;
      // 校验分组字段
      const tags = select.getSelectTags();
      if (!tags || tags.length === 0) {
        alert('存在字段未选择，请检查');
        return;
      }
      disabled = true;
      btn.classList.add('data-mode-btn-disabled');

      this.onclick(tags);
      setTimeout(() => {
        disabled = false;
        btn.classList.remove('data-mode-btn-disabled');
      }, 2000);
    });
    div.appendChild(btn);
    return div;
  }

  data2option(data) {
    const option = [];
    for (const key in data) {
      const d = data[key];
      option.push({ value: d.key, text: d.text });
    }
    return option;
  }
}
